package com.itheima.ydd.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.R;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.SysRoleDto;
import com.itheima.ydd.dto.SysUserAddDto;
import com.itheima.ydd.dto.SysUserDto;
import com.itheima.ydd.dto.SysUserPageDto;
import com.itheima.ydd.entity.SysRole;
import com.itheima.ydd.entity.SysRoleMenu;
import com.itheima.ydd.entity.SysUser;
import com.itheima.ydd.service.ISysRoleMenuService;
import com.itheima.ydd.service.ISysRoleService;
import com.itheima.ydd.service.ISysUserService;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author author
 * @since 2022-05-22
 */
@RestController
@RequestMapping("/sys_user")
@Slf4j
@CrossOrigin
public class SysUserController {
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private ISysRoleService iSysRoleService;
    @Autowired
    private ISysRoleMenuService iSysRoleMenuService;



    @PostMapping("update")
    public ResultData upDate(@RequestBody SysUserAddDto sysUserAddDto){
        String password = sysUserAddDto.getPassword();
        if (password!=null){
            //对密码进行MD5加密
            String s3 = DigestUtils.md5DigestAsHex(password.getBytes());
            sysUserAddDto.setPassword(s3);
        }
        String roleId = sysUserAddDto.getRoleId();
        log.info("roleId:{}",roleId);

            List<String> roleIdList = sysUserAddDto.getRoleIdList();
            String s = roleIdList.toString().replaceAll(" ","");
            String s1 = s.replaceAll("\\[", "[\"");
            String s2 = s1.replaceAll("]", "\"]");
            sysUserAddDto.setRoleId(s2);
            iSysUserService.updateById(sysUserAddDto);

        return ResultData.ok("","修改成功");
    }


    /**
     * 查询管理员详情
     * @param id
     * @return
     */
    @GetMapping("rowInfo")
    public ResultData rowInfo(String id){
        LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(id!=null,SysUser::getId,id);
        // 获取当前id对象
        SysUser one = iSysUserService.getOne(lqw);
        // 创建dto对象
        SysUserAddDto sysUserAddDto = new SysUserAddDto();
        BeanUtils.copyProperties(one,sysUserAddDto);
        // 获取用户角色id
        String roleIds = sysUserAddDto.getRoleId();
        log.info("roeIds:{}",roleIds);

        // 去除 [" "]
        String substring = roleIds.substring(2, roleIds.length() - 2);
        // 以 ,切割
        String[] split = substring.split(",");
        for (String s : split) {
            sysUserAddDto.getRoleIdList().add(s);
        }
        return ResultData.ok("",sysUserAddDto);
    }

    /**
     * 删除用户数据
     * @param sysUser
     * @return
     */
    @GetMapping("del")
    public ResultData del(SysUser sysUser){

        LambdaQueryWrapper <SysUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(sysUser.getId()!=null,SysUser::getId,sysUser.getId());
        iSysUserService.remove(lqw);

        return ResultData.ok("","删除成功");
    }



    /**
     * 添加用户数据
     * @param sysUserAddDto
     * @return
     */
    @PostMapping("add")
    public ResultData add(@RequestBody SysUserAddDto sysUserAddDto){
        // 判断账号名是否重复
        String loginName = sysUserAddDto.getLoginName();
        String phone = sysUserAddDto.getPhone();
        String email = sysUserAddDto.getEmail();
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getLoginName,loginName);
        SysUser loginNameOne = iSysUserService.getOne(lambdaQueryWrapper);
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(SysUser::getPhone,phone);
        SysUser phoneOne = iSysUserService.getOne(lambdaQueryWrapper1);
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper2.eq(SysUser::getEmail,email);
        SysUser emailOne = iSysUserService.getOne(lambdaQueryWrapper2);


        if (loginNameOne != null || phoneOne != null || emailOne != null ){
            return ResultData.error("账号,手机号,邮箱 不能重复");
        }

        sysUserAddDto.setId(IdWorker.getId()+"");
        //对密码进行md5加密
        String password = sysUserAddDto.getPassword();
        String s3 = DigestUtils.md5DigestAsHex(password.getBytes());

        sysUserAddDto.setPassword(s3);

        List<String> roleIdList = sysUserAddDto.getRoleIdList();
        log.info("roleIdList------- :{}",roleIdList);
        String s = roleIdList.toString().replaceAll(" ","");
        log.info("s:{}",roleIdList.toString());
        String s1 = s.replaceAll("\\[", "[\"");
        log.info("s1:{}",s1);
        String s2 = s1.replaceAll("]", "\"]");
        log.info("s2:{}",s2);
        sysUserAddDto.setRoleId(s2);
        //设置默认id
        sysUserAddDto.setDefaultData("1");
        sysUserAddDto.setCreateDate(LocalDateTime.now());
        iSysUserService.save(sysUserAddDto);



        ResultData resultData = new ResultData();
        resultData.setData("");
        resultData.setErrmsg("修改成功");
        resultData.setErrno(0);
        return resultData;
    }


    /**
     * 用户分页
     */
    @GetMapping("list")
    public ResultData list(Integer page, Integer limit, String login_name,String phone,Integer status){
        /*// 1.账号
        String loginName = sysUser.getLoginName();
        // 2.手机
        String phone = sysUser.getPhone();
        // 3.账号状态
        Integer status = sysUser.getStatus();*/
        log.info("前端传来数据{},{},{}",page,limit,login_name,phone,status);
        // 分页构建器
        Page pageInfo = new Page();
        // 条件构建器
        LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper();
        // 添加条件
         // 1. 账号条件&& !loginName.equals("")
        lqw.like(login_name !=null ,SysUser::getLoginName, login_name);
         // 2. 手机条件 && !phone.equals("")
        lqw.like(phone!=null,SysUser::getPhone,phone);
         // 3. 账号状态条件
        lqw.eq(status!=null,SysUser::getStatus,status);
         // 4. 排序
        lqw.orderByDesc(SysUser::getCreateDate);

        // 调用查询分页数据
        iSysUserService.page(pageInfo, lqw);

        // 获取当前页数据
        List<SysUser> records = pageInfo.getRecords();

        List<SysUserDto> sysUserDtos = new ArrayList<>();

        // 处理数据
        sysUserDtos = records.stream().map((item) -> {
            SysUserDto sysUserDto = new SysUserDto();
            // 对拷
            BeanUtils.copyProperties(item,sysUserDto);
            // 获取 角色id
            String roleId = item.getRoleId();
            log.info("roleId:{}",roleId);
            // 处理id   去除 "[ ]"
            String substring = roleId.substring(2, roleId.length() - 2);
            log.info("substring:{}",substring);
             // 以 , 切割
            String[] split = substring.split(",");
            List<String> nameList = new ArrayList<>();
            for (String s : split) {
                log.info("s:{}",s);
                //String substring1 = s.substring(2, s.length() - 2);
                // 根据 id 查 角色名字
                SysRole byId = iSysRoleService.getById(s);
                log.info("byId:{}",byId);
                String name = byId.getName();
                nameList.add(name);
            }
            sysUserDto.setRoleName(nameList);

            //sysUserDtos.add(sysUserDto);
            return sysUserDto;
        }).collect(Collectors.toList());
        SysUserPageDto sysUserPageDto = new SysUserPageDto();
        sysUserPageDto.setCount(Math.toIntExact(pageInfo.getTotal()));//总数
        sysUserPageDto.setCurrenPage(Math.toIntExact(pageInfo.getCurrent())); //当前页码

        sysUserPageDto.setPageSize(Math.toIntExact(pageInfo.getSize()));//每页数量
        sysUserPageDto.setTotalPages(Math.toIntExact(pageInfo.getPages()));//总页数
        sysUserPageDto.setData(sysUserDtos);




        return ResultData.ok("",sysUserPageDto);
    }


}
